import {lazyReportCache} from '../utils/report.js'
import {onCachePageshow, getPagePath} from '../utils/common.js'

/**
 * 监听缓存中页面显示的加载时间
 *
 * */
export default function observerLoad() {
    ['load', 'DOMContentLoaded'].forEach(type => onEvent(type))
    
    onCachePageshow(event => {
        requestAnimationFrame(() => {
            ['load', 'DOMContentLoaded'].forEach(type => {
                const data = {
                    type: 'performance',
                    subType: type.toLocaleLowerCase(),
                    pagePath: getPagePath(),
                    startTime: performance.now() - event.timeStamp,
                    bfc: true,
                }
                lazyReportCache(data)
            })
        })
    })
}

function onEvent(type) {
    function callback() {
        const data = {
            type: 'performance',
            subType: type.toLocaleLowerCase(),
            startTime: performance.now(),
        }
        lazyReportCache(data)
        window.removeEventListener(type, callback, true)
    }
    
    window.addEventListener(type, callback, true)
}
